package exsun.jt808.data.media.operate.encode.codec;

import exsun.jt808.data.config.MediaEncoding;
import exsun.jt808.data.media.data.MediaConfig;

import java.util.concurrent.ConcurrentHashMap;

/**
 * g711a/u转aac
 */
public class EasyAacCodec implements CodecBase{
    //存放Easy_AACEncoder的每个设备通道对应的音频编码handle
    private ConcurrentHashMap<String, Long> handleMap = new ConcurrentHashMap();
    private Integer audioCodec;

    public EasyAacCodec(MediaEncoding.Encoding audioCodeType){
        this.audioCodec = getAudioCodec(audioCodeType);
    }

    private int getAudioCodec(MediaEncoding.Encoding audioCodeType){
        if(audioCodeType == MediaEncoding.Encoding.G711U){
            return 0;
        }
        if(audioCodeType == MediaEncoding.Encoding.G711A){
            return 1;
        }
        //        mediaMap.put(8,0);未验证
        return 0;
    }


    @Override
    public void init(MediaConfig config, String clientChannelId) {
        if(this.audioCodec == null)return;
        if(handleMap.containsKey(clientChannelId)){
            release(clientChannelId);
        }
        Long handle = Easy_AACEncoder.Easy_AACEncoder_Init(config.sampleRate,(byte)config.audioChannel, config.sampleBits,(byte)(int)audioCodec, config.rateBits);
        handleMap.put(clientChannelId, handle);
    }
    @Override
    public byte[] decode(String clientChannelId, byte[] data) {
        Long handle = handleMap.get(clientChannelId);
        if(handle == null||data == null||data.length == 0)return new byte[0];
        return Easy_AACEncoder.Easy_AACEncoder_Encode(handle, data);
    }
    @Override
    public void release(String clientChannelId) {
        Long handle = handleMap.remove(clientChannelId);
        if(handle == null)return;
        Easy_AACEncoder.Easy_AACEncoder_Release(handle);
    }
}
